﻿using Smobiler.Core;
using Smobiler.Core.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using Model;
using System.Web.Script.Serialization;
using FubiManger.Controls;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace FubiManger.UI
{
    partial class OrdinfoForm : Smobiler.Core.Controls.MobileForm
    {
        public OrdinfoForm() : base()
        {
            //This call is required by the SmobilerForm.
            InitializeComponent();
        }
        ms_order order = new ms_order();
        /// <summary>
        /// 订单号
        /// </summary>
        public string ordsn { get; set; }
        /// <summary>
        /// 1管理员2收银3员工
        /// </summary>
        public string stype { get; set; }
        /// <summary>
        /// 商户ID
        /// </summary>
        public string mid { get; set; }
        private const string tokenurl = "https://api.weixin.qq.com/cgi-bin/token";
        ms_merchant merchant = new ms_merchant();

        private void panclose_Press(object sender, EventArgs e)
        {
            this.Close();
        }

        private void OrdinfoForm_Load(object sender, EventArgs e)
        {
            // ordid = "7";
            //if (stype != "1")
            //{
            //    panclear.Height = 0;               
            //}
            order = orderDal.Querybysn(ordsn);
            merchant = merchantDal.Querybyid(order.merchant_id);
            imgcode.ResourceID = @"C:\paycode\" + merchant.wechat_code;

            if (order.consignee_tel.Length == 11)
                btntel.Text = order.consignee_tel;
            //else
            //    lbltel.Text = "现场下单";

            if (order.pay_type == "4" && order.status == "1")
            {
                if (stype == "1")
                {
                    pancode.Visible = true;
                    lblbvcode.Visible = true;
                }
            }
            lblordsn.Text = order.order_sn;//订单编号
            lbltime.Text = Convert.ToDateTime(order.add_time).ToString("yyyy-MM-dd HH:mm:ss");
            lblprice.Text = "￥" + Convert.ToDouble(order.order_price).ToString("f2");//实付金额
            //if (order.status == "4")
            //{
            //    btnsub.Enabled = true;
            //}
            if (order.ordtype == "2")
                btnsub.Enabled = true;

            //if (order.codestatus == "1")
            //{
            //    panclear.Visible = true;
            //    imgbg.ResourceID = "ordinfobg1";
            //}
            //else
            //{
            //    panclear.Visible = false;
            //    imgbg.ResourceID = "ordinfobg";
            //}
            //if (order.is_online == "2")
            //    btnscan.Text = "完成订单";
            //else
            //{
            //    if (order.status == "6")
            //    {
            //        btnscan.Enabled = false;
            //        btnscan.Text = "已完成";
            //    }
            //    else if (order.status == "7")
            //    {
            //        btnscan.Text = "退款";
            //    }
            //    else if (order.status == "2")//已支付
            //    {
            //        btnclare.Width = 150;
            //        btnclare.Visible = true;
            //        if (order.u_sage == "1")
            //            btnscan.Text = "扫码核销";

            //    }
            //    else if (order.status == "3")//待发货
            //    {
            //        btnscan.Text = "发物流";
            //    }
            //    else if (order.status == "5")//已发货
            //    {
            //        btnscan.Text = "待收货";
            //    }
            //}
            //if (order.orderremark.Length > 3)
            //    lblremark.Text = order.orderremark;//备注
            //else
            //{
            //    pantp.Height = 98;
            //    lblremark.Visible = false;

            //}
            JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
            List<Gdpro> prolist = js.Deserialize<List<Gdpro>>(order.goods_info);
            panpros.Height = prolist.Count * 44;
            panord.Height = panpros.Height + 30;
            panbtm.Location = new System.Drawing.Point(0, panord.Height + 100);
            panall.Height = panord.Height + pantp.Height + 40;
            for (int i = 0; i < prolist.Count; i++)
            {
                ordergpcontrol con = new ordergpcontrol();
                con.proname = prolist[i].proname;
                con.cout = "x " + prolist[i].count;
                con.price = "￥ " + prolist[i].price;
                panpros.Controls.Add(con);
            }
            if (order.merchant_id == "2")
                btnsub.Text = "完成配送";
        }
        /// <summary>
        /// 调用扫描
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnscan_Press(object sender, EventArgs e)
        {
            if (btnscan.Text == "完成订单")
            {
                MessageBox.Show("点击确定将完成订单", "订单提示", MessageBoxButtons.OKCancel, (obj, args) =>
                {
                    if (args.Result == ShowResult.OK)
                    {
                        if (orderDal.Updatecodestatus(ordsn) > 0)
                        {
                            //Toast("订单核销成功");
                            this.Close();
                        }
                    }
                });
            }
            else if (btnscan.Text == "扫码核销")
                bscan.GetBarcode();
            else
            {
                //发物流
                LogisticsForm frm = new LogisticsForm();
                frm.ordsn = ordsn;//订单号
                this.Form.Show(frm, true, (obj, args) =>
                {
                    order = orderDal.Querybysn(ordsn);
                    if (order.status == "5")//待发货
                    {
                        btnscan.Text = "待收货";
                    }
                });

            }
        }

        private void bscan_BarcodeScanned(object sender, BarcodeResultArgs e)
        {
            try
            {
                if (e.isError == false)
                {
                    Array temp1 = e.Value.Split('&');
                    Array temp2 = temp1.GetValue(1).ToString().Split('=');//获取商户信息
                    string merchantid = temp2.GetValue(1).ToString();//获取商户编号
                    Array temp4 = temp1.GetValue(0).ToString().Split('=');//获取订单信息
                    string ordsn = temp4.GetValue(1).ToString();//获取订单号
                    Array temp5 = temp1.GetValue(2).ToString().Split('=');//获取核销信息
                    string status = temp5.GetValue(1).ToString();//获取核销状态
                    if (status == "2")
                    {
                        MessageBox.Show("该订单已核销");
                    }
                    else
                    {
                        if (merchantid != order.merchant_id)
                        {
                            MessageBox.Show("该订单不属于您");
                        }
                        else
                        {
                            MessageBox.Show("点击确定将核销订单", "核销提示", MessageBoxButtons.OKCancel, (obj, args) =>
                            {
                                if (orderDal.Updatecodestatusscan(ordsn) > 0)//扫码核销订单
                                {
                                    Toast("订单核销成功");
                                    this.Close();
                                }
                            });
                        }
                    }
                }
            }
            catch (Exception)
            {

                Toast("二维码无法识别");
            }
        }
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnclare_Press(object sender, EventArgs e)
        {
            MessageBox.Show("点击确定取消订单", "操作提示", MessageBoxButtons.OKCancel, (obj, args) =>
            {
                if (args.Result == ShowResult.OK)
                {
                    orderDal.Clearordsn(ordsn);
                    Toast("订单取消成功");
                    this.Close();
                }
            });

        }
        /// <summary>
        /// 支付宝收款码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnalipay_Press(object sender, EventArgs e)
        {
            btnwechat.ForeColor = System.Drawing.Color.DarkGray;
            btnalipay.ForeColor = System.Drawing.Color.FromArgb(43, 140, 255);
            imgcode.ResourceID = @"C:\paycode\" + merchant.alipay_code;
        }
        /// <summary>
        /// 微信收款码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnwechat_Press(object sender, EventArgs e)
        {
            btnalipay.ForeColor = System.Drawing.Color.DarkGray;
            btnwechat.ForeColor = System.Drawing.Color.FromArgb(43, 140, 255);
            imgcode.ResourceID = @"C:\paycode\" + merchant.wechat_code;
        }
        /// <summary>
        /// 完成配送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnsub_Press(object sender, EventArgs e)
        {
            msgcontrol con = new msgcontrol();
            con.title = "操作提示";
            con.content = "您是否需要完成该操作";
            this.Form.ShowDialog(con, (obj, args) =>
            {
                if (con.flag == true)
                {
                    if (order.merchant_id == "2")
                    {
                        orderDal.Updatestatus(order.order_sn,"6");
                        this.Close();
                    }
                    else
                    {
                        string o_ordersn = "Y" + DateTime.Now.ToString("yyyyMMddHHmmss");
                        h_order ord = new h_order();
                        ord.o_ordersn = o_ordersn;//订单号
                        ord.o_shop_name = merchant.merchant_name;//商户名称
                        ord.o_residential = order.consignee_address;//小区
                        ord.o_tel = merchant.contact_person_tel;//联系电话
                        ord.o_delivery_fee = Convert.ToDouble(merchant.distribution_costs).ToString("f2");//配送费
                        ord.o_pickup_address = merchant.address;//商家地址
                        ord.o_delivery_time_start = DateTime.Now.ToString("yyyy-MM-dd" + " 11:45");//起始时间
                        ord.o_delivery_time_end = DateTime.Now.ToString("yyyy-MM-dd" + " 12:45");//结束时间
                        ord.o_delivery_address = order.consignee_address;//商家地址
                        ord.o_create_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//创建时间 
                        h_orderDal.Addord(ord);
                        List<Gdpro> gdpros = new List<Gdpro>();
                        string goodinfo = "";
                        JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                        gdpros = js.Deserialize<List<Gdpro>>(order.goods_info);
                        h_order_goods good = new h_order_goods();
                        good.og_oordersn = o_ordersn;
                        good.og_ordersn = order.order_sn;
                        good.og_delivery_fee = merchant.distribution_costs;
                        for (int i = 0; i < gdpros.Count; i++)
                        {
                            if (i == 0)
                                goodinfo = gdpros[i].proname + "*" + gdpros[i].count;
                            else
                                goodinfo += "+" + gdpros[i].proname + "*" + gdpros[i].count;
                        }
                        good.og_goodsinfo = goodinfo;//商品
                        good.og_tel = order.consignee_tel;//收货人电话
                        good.og_nickname = order.consignee_name;//收货人
                        good.og_delivery_address = order.consignee_address;//收货地址
                        good.og_paysn = order.pay_sn;//支付编号
                        good.og_openid = order.openid;//openid
                        h_orderDal.Addgoods(good);
                        orderDal.Updatestatus(order.order_sn,"4");
                        Send(order.pay_sn, order.openid);
                        this.Close();
                    }
                }
            });
            
        }
        /// <summary>
        /// 发货通知
        /// </summary>
        /// <param name="out_trade_no"></param>
        /// <param name="openid"></param>
        private void Send(string out_trade_no, string openid)
        {
            SortedDictionary<string, string> payDict = new SortedDictionary<string, string>();
            List<Shiplist> splist = new List<Shiplist>();
            Shiplist sping = new Shiplist();
            sping.item_desc = "外卖";
            splist.Add(sping);
            Openkey op = new Openkey();
            op.openid = openid;
            orderkey odk = new orderkey();
            odk.order_number_type = "1";
            odk.out_trade_no = out_trade_no;
            odk.mchid = "1645910188";
            Shipping ship = new Shipping();
            ship.order_key = odk;
            ship.delivery_mode = "1";
            ship.logistics_type = "4";
            ship.shipping_list = splist;
            ship.upload_time = "2022-12-15T13:29:35.120+08:00";
            ship.payer = op;
            string param1 = JsonConvert.SerializeObject(ship);
            //string str = param1.Replace("\\","");
            string param = "grant_type=client_credential&appid=wx5f37feb4be8e16f3&secret=070534f3f823ff12b6b6e3064ea5dded";

            string result = requestGet(tokenurl, param);
            JObject json = (JObject)JsonConvert.DeserializeObject(result);
            string token = json["access_token"].ToString();
            string url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" + token;
            requestPost(url, param1);
        }
        /*
        * HTTP的Get请求方式
        * strUrl 请求地址
        * param 请求数据
        */
        public string requestGet(string strUrl, string param)
        {


            HttpWebRequest httpWebRequest = WebRequest.Create(strUrl + "?" + param) as HttpWebRequest;
            httpWebRequest.Method = "GET";      //指定允许数据发送的请求的一个协议方法
            httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";       //设置 ContentType 属性设置为适当的值
            WebResponse webResponse = httpWebRequest.GetResponse() as HttpWebResponse;        //发起请求,得到返回对象
            Stream dataStream = webResponse.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
            string returnStr = reader.ReadToEnd();
            // Clean up the streams and the response.
            reader.Close();
            webResponse.Close();
            return returnStr;
        }
        public string requestPost(string strUrl, string param)
        {


            HttpWebRequest httpWebRequest = WebRequest.Create(strUrl) as HttpWebRequest;
            httpWebRequest.Method = "POST";      //指定允许数据发送的请求的一个协议方法
            httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";       //设置 ContentType 属性设置为适当的值
            byte[] data = Encoding.UTF8.GetBytes(param);
            using (Stream stream = httpWebRequest.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);     //写入数据
            }
            WebResponse webResponse = httpWebRequest.GetResponse() as HttpWebResponse;        //发起请求,得到返回对象
            Stream dataStream = webResponse.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
            string returnStr = reader.ReadToEnd();
            // Clean up the streams and the response.
            reader.Close();
            webResponse.Close();
            return returnStr;

        }

        private void btntel_Press(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(btntel.Text))
            {
                this.Client.TelCall(btntel.Text);
            }
        }
    }
}


public class Shipping
{

    public string delivery_mode { get; set; }
    public string logistics_type { get; set; }
    public orderkey order_key { get; set; }
    public Openkey payer { get; set; }
    public List<Shiplist> shipping_list { get; set; }
    public string upload_time { get; set; }

}
public class Openkey
{
    public string openid { get; set; }
}
public class Shiplist
{
    public string item_desc { get; set; }
}

public class orderkey
{
    public string order_number_type { get; set; }
    public string out_trade_no { get; set; }
    public string mchid { get; set; }
}